package com.bank.service;

import com.bank.entity.Transaction;
import com.bank.entity.CardInfo;
import com.bank.repository.TransactionRepository;
import com.bank.repository.CardInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;

@Service
@Transactional
public class TransactionService {
    @Autowired
    private TransactionRepository transactionRepository;

    @Autowired
    private CardInfoRepository cardInfoRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 插入交易记录（无id字段）
    public void insertTrade(Transaction transaction) {
        String sql = "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (?, ?, ?, ?, ?)";
        try {
            int rows = jdbcTemplate.update(sql,
                    transaction.getTradeDate(),
                    transaction.getTradeType(),
                    transaction.getCardID(),
                    transaction.getTradeMoney(),
                    transaction.getRemark()
            );
            System.out.println("tradeinfo插入返回行数：" + rows);
            if (rows == 0) {
                System.err.println("警告：tradeinfo插入0行，可能未成功！");
            }
        } catch (Exception e) {
            System.err.println("插入tradeinfo异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    public List<Transaction> findRecentByCardID(String cardID) {
        return transactionRepository.findTop10ByCardIDOrderByTradeDateDesc(cardID);
    }

    public List<Transaction> findByKeyword(String keyword) {
        // 1. 查找所有客户姓名或卡号包含关键字的银行卡
        List<CardInfo> cards = cardInfoRepository.findByCardIDOrCustomerName(keyword);
        
        // 2. 提取这些卡的ID
        List<String> cardIDs = cards.stream()
                                    .map(CardInfo::getCardID)
                                    .collect(Collectors.toList());
        
        // 3. 将原始关键字也加入搜索列表（以防有卡号能匹配上但客户姓名不能）
        if (!cardIDs.contains(keyword)) {
            cardIDs.add(keyword);
        }
        
        // 4. 如果没找到任何相关卡号，返回空列表
        if (cardIDs.isEmpty()) {
            return new ArrayList<>();
        }

        // 5. 根据卡号列表查询交易记录
        return transactionRepository.findByCardIDIn(cardIDs);
    }

    public List<Transaction> findAll() {
        return transactionRepository.findAll();
    }

    // 删除交易记录：只能用cardID+tradeDate等复合条件，示例用原生SQL
    public void deleteByCardIDAndTradeDate(String cardID, Date tradeDate) {
        String sql = "DELETE FROM tradeinfo WHERE cardID = ? AND tradeDate = ?";
        jdbcTemplate.update(sql, cardID, tradeDate);
    }
} 